#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>


// Clients
WiFiClient espClient;
PubSubClient client(espClient);
aREST rest = aREST(client);// Create aREST instance

// Unique ID to identify the device for cloud.arest.io
char* device_id = "your-id";
const char* ssid = "your-wifi";
const char* password = "your-wifi-password";

bool ledState;
void callback(char* topic, byte* payload, unsigned int length) // Handles message arrived on subscribed topic(s)
{
  rest.handle_callback(client, topic, payload, length);
}

int toggle(String command)// Custom function accessible by the API 
{
  ledState=!ledState;
  digitalWrite(D5,ledState);
  return 1;
}



void setup(void)
{
  Serial.begin(115200);
  // Set callback
  client.setCallback(callback);
   // Function to be exposed
  rest.function("toggle",toggle);
  // Give name and ID to device
  rest.set_id(device_id);
  rest.set_name("your-name");
  ledState=false;
  pinMode(D5,OUTPUT);
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  // Set output topic
  char* out_topic = rest.getBuffer();

}
void loop() 
{
  rest.loop(client);// Connect to the cloud
}

